package com.aaa.controller;

import com.aaa.entity.Menu;
import com.aaa.entity.Role;
import com.aaa.exception.SaveRoleMenuException;
import com.aaa.service.MenuService;
import com.aaa.service.RoleService;
import com.aaa.util.DefaultMsg;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @RequestMapping("/selectAll")
    public PageInfo<Role> selectAll(String rname, Integer currentPage, Integer pageSize){
        PageHelper.startPage(currentPage,pageSize);
        QueryWrapper<Role> wrapper=new QueryWrapper<Role>();
        wrapper.like("rname",rname);
        List<Role> list = roleService.list(wrapper);
        PageInfo<Role> pageInfo=new PageInfo<Role>(list);
        return pageInfo;
    }
    @RequestMapping("/saveOrUpdate")
    public DefaultMsg saveOrUpdate(Role role){
        DefaultMsg defaultMsg=new DefaultMsg();
        boolean b = roleService.saveOrUpdate(role);
        if (!b){
            defaultMsg.setCode(500);
            defaultMsg.setSuccess(0);
            defaultMsg.setError("操作失败");
        }
        return defaultMsg;
    }
    @RequestMapping("/delete")
    public DefaultMsg delete(Integer rid){
        DefaultMsg defaultMsg=new DefaultMsg();
        boolean b = roleService.removeById(rid);
        if (!b){
            defaultMsg.setCode(500);
            defaultMsg.setSuccess(0);
            defaultMsg.setError("操作失败");
        }
        return defaultMsg;
    }
    @RequestMapping("/selectAllMenu")
    public List<Menu> selectAllMenu(){
        List<Menu> menus = menuService.selectAllMenu();
        return menus;
    }
    @RequestMapping("/selectQxId")
    public List<Integer> selectQx(Integer rid){
        List<Integer> menus = menuService.selectQxId(rid);
        return menus;
    }
    @RequestMapping("/insertPremit")
    public DefaultMsg insertPermit(Integer rid,String mids){
        DefaultMsg defaultMsg;
        try{
             defaultMsg = new DefaultMsg();
            defaultMsg.setTarget(roleService.insertPermit(rid, mids));
        }catch (SaveRoleMenuException e){
            e.printStackTrace();
            defaultMsg=new DefaultMsg();
            defaultMsg.setSuccess(0);
            defaultMsg.setError("操作失败，后端报错");
        }
        return defaultMsg;
    }
}
